package com;

import java.util.BitSet;

public class BitSetTest {
	public static void main(String[] args) {
		sortArray();
//		simpleExample();
//		BitSet bit = new BitSet(64);
	}

	public static void sortArray() {
		int[] array = new int[] { 1, 2, 500, 14, 34, 76, 678, 4354, 899, 1, 2 };

		BitSet bit = new BitSet(64);
		System.out.println("bit.size()=" + bit.size());
		
		for (int i = 0; i < array.length; i++) {
			bit.set(array[i]);
		}
		// 剔除重复数字后的元素个数
		int bitLen = bit.cardinality();

		System.out.println("bitLen=" + bitLen);
		
		System.out.println("bit=" + bitSet2ByteArray(bit));

		// 源码中的遍历方法
		// To iterate over the true bits in a BitSet, use the following loop:

		for (int i = bit.nextSetBit(0); i >= 0; i = bit.nextSetBit(i + 1)) {
			// operate on index i here
			
			System.out.println("i=" + i);
		}

	}

	/**
	 * 将BitSet对象转化为ByteArray
	 * 
	 * @param bitSet
	 * @return
	 */
	public static byte[] bitSet2ByteArray(BitSet bitSet) {
		byte[] bytes = new byte[bitSet.size() / 8];
		for (int i = 0; i < bitSet.size(); i++) {
			int index = i / 8;
			int offset = 7 - i % 8;
			bytes[index] |= (bitSet.get(i) ? 1 : 0) << offset;
		}
		return bytes;
	}

	/**
	 * 将ByteArray对象转化为BitSet
	 * 
	 * @param bytes
	 * @return
	 */
	public static BitSet byteArray2BitSet(byte[] bytes) {
		BitSet bitSet = new BitSet(bytes.length * 8);
		int index = 0;
		for (int i = 0; i < bytes.length; i++) {
			for (int j = 7; j >= 0; j--) {
				bitSet.set(index++, (bytes[i] & (1 << j)) >> j == 1 ? true
						: false);
			}
		}
		return bitSet;
	}

	
	 /**
     * 简单使用示例
     */
    public static void simpleExample() {
        String names[] = { "Java", "Source", "and", "Support" };
        BitSet bits = new BitSet();
        for (int i = 0, n = names.length; i < n; i++) {
            if ((names[i].length() % 2) == 0) {
                bits.set(i);
            }
        }
 
        System.out.println(bits);
        System.out.println("Size : " + bits.size());
        System.out.println("Length: " + bits.length());
        for (int i = 0, n = names.length; i < n; i++) {
            if (!bits.get(i)) {
                System.out.println(names[i] + " is odd");
            }
        }
        BitSet bites = new BitSet();
        bites.set(0);
        bites.set(1);
        bites.set(2);
        bites.set(3);
        bites.andNot(bits);
        System.out.println(bites);
    }
 
}
